import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class munber_Exception  extends Exception{  //异常处理
    String e;
    public munber_Exception(String message){

        this.e=message;
    }
    public String shows(){
        return e;

    }
}

class cal extends JFrame implements ActionListener {
    private JPanel p1, p2;
    private JTextArea show;
    JMenuBar menubar;
    JMenu  menu;
    StringBuilder strA;
    StringBuffer strB;

    char oper = '~';
    double A;
    double B;
    private String[] text2 = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", "+/-", ".", "+",
            "1/x", "%", "sqrt", "="
    };//计算器按钮面板
    private JButton[] munButton = new JButton[text2.length];

    public cal() {
        p1 = new JPanel();
        p2 = new JPanel();
        show = new JTextArea();
        p1.setSize(600, 100);
        menubar = new JMenuBar();

        menu = new JMenu("编辑(E)");


        strB = new StringBuffer();
       // strA = new StringBuffer();
        strA = new StringBuilder();


    }

    public void init() {//初始化
        this.setTitle("计算器");
        this.setBounds(200, 200, 320, 300);
        this.setLayout(new BorderLayout());
        this.add(p1, BorderLayout.CENTER);

        JPanel centerPanel = new JPanel();
        JButton button2 = new JButton("Backpace");
        JButton button3 = new JButton("C");
                button2.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JOptionPane.showMessageDialog(null, "回退");
                        String text = show.getText();
                        if (!text.isEmpty()) {
                            text = text.substring(0, text.length() - 1); // 删除最后一个字符
                            show.setText(text);  // 更新文本框内容
                            // 更新相关变量中的内容
                            if (text.equals("")) {
                                strA = new StringBuilder();  // 如果文本框为空，将相关变量置空字符串
                            } else {
                                strA = new StringBuilder(text);  // 更新相关变量内容为删除最后一个字符后的文本内容
                            }
                        }
                    }
                });

        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "清空");
                A = Double.parseDouble(String.valueOf(strA));
                show.setText(" ");
                oper = '~';
                int len1 = strA.length();
                strA.delete(0, len1);

            }
        });

        centerPanel.add(button2);
        centerPanel.add(button3);

        p1.add(centerPanel, BorderLayout.CENTER);

        show.setPreferredSize(new Dimension(320, 80));
        p1.add(show);

        //调节按钮大小
        button2.setPreferredSize(new Dimension(160, 40));
        button3.setPreferredSize(new Dimension(160, 40));// 设置首选宽高

        this.add(p2, BorderLayout.SOUTH);
        menubar.add(menu);
        this.setJMenuBar(menubar);
        this.setLocationRelativeTo(null);
        this.setResizable(false);

        show.setPreferredSize(new Dimension(300, 50));
        p1.add(show);
        p2.setLayout(new GridLayout(5, 4, 2, 3));
        //添加数字按键
        for (int i = 0; i < text2.length; i++) {
            munButton[i] = new JButton(text2[i] + " ");
            p2.add(munButton[i]);

        }


        for (int i = 0; i < munButton.length; i++)
            munButton[i].addActionListener(this);

        this.setVisible(true);


        this.addWindowListener(new WindowAdapter() { //监听窗体事件
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    }


    public double division(double x, double y) throws munber_Exception {

        if (y == 0) {
            throw new munber_Exception("除数不能为0！");
        } else {
            return x / y;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            String act = e.getActionCommand();//返回事件源label标签的字符串
            act = act.trim();
            // 单个或多个字符
            // 单个字符
            if (null != act && act.length() == 1) {
                char a = act.charAt(0);//取act这个字符串的首字符
                if (a == '0' || a == '1' || a == '2' || a == '3' || a == '4' || a == '5' || a == '6' || a == '7' || a == '8' || a == '9' || a == '.') {
                    if (oper == '~') {
                        strA.append(a);
                        show.setText(String.valueOf(strA));
                    } else {
                        strB.append(a);
                        show.setText(String.valueOf(strA) + oper + String.valueOf(strB));
                    }
                } else if (a == '+' || a == '-' || a == '/' || a == '*' || a == '%') {
                    oper = a;
                    show.setText(String.valueOf(strA) + oper);

                } else if (a == '=') {

                    A = Double.parseDouble(String.valueOf(strA));
                    B = Double.parseDouble(String.valueOf(strB));
                    double j;
                    int len1 = strA.length();
                    int len2 = strB.length();

                    if (oper == '+') {
                        j = A + B;
                        show.setText(Double.toString(j));

                        strA.delete(0, len1);
                        strB.delete(0, len2);
                        strA.append(j);

                    } else if (oper == '-') {
                        j = A - B;
                        show.setText(Double.toString(j));

                        strA.delete(0, len1);
                        strB.delete(0, len2);
                        strA.append(j);
                    } else if (oper == '*') {
                        j = A * B;
                        show.setText(Double.toString(j));

                        strA.delete(0, len1);
                        strB.delete(0, len2);
                        strA.append(j);
                    } else if (oper == '/') {
                        try {
                            j = division(A, B);
                            show.setText(Double.toString(j));
                        } catch (munber_Exception u) {
                            show.setText(u.shows());
                        }
                    } else if (oper == '%') {
                        j = A % B;
                        show.setText(Double.toString(j));

                        strA.delete(0, len1);
                        strB.delete(0, len2);
                        strA.append(j);

                    }

                }
            } else if (null != act && act.length() > 1) {
                if (act.contains("sqrt")) {
                    double value = Double.parseDouble(show.getText());
                    double result = Math.sqrt(value);
                    show.setText(Double.toString(result));
                } else if (act.contains("1/x")) {
                    double value = Double.parseDouble((show.getText()));
                    if (value != 0) {
                        double result = 1 / value;
                        show.setText(Double.toString(result));
                    } else {
                        show.setText("除数不能为0！");
                    }
                } else if (act.contains("+/-")) {
                    String currentText = show.getText();
                    if (!currentText.equals("")) {
                        if (currentText.charAt(0) == '-') {
                            show.setText(currentText.substring(1));
                        } else {
                           show.setText("-" + currentText);
                        }
                }

                }
            }

        }

         catch(NumberFormatException ex){
                show.setText("输入格式错误");
            }
        }

    }
public class Calculator {
    //调用
    public static void main(String[] args) {
        cal Calculator = new cal();
        Calculator.init();
    }
}

